/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.vistas;

import com.mycompany.Controlador.GenericController;
import com.mycompany.entidades.Articulo;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 * @author johnny
 */
public class VSeleccionArticulo extends javax.swing.JFrame {

    /**
     * Creates new form VSeleccionArticulo
     */
    GenericController<Articulo> controlador = new GenericController();
    List<Articulo> listaArticulos;
    Articulo art = new Articulo();
    int tipoI = 0;
    boolean factura;

    public VSeleccionArticulo(boolean factura) {
        this.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/img/1362798841_CellPhone.png")).getImage());
        initComponents();
        this.factura = factura;
        listaArticulos = controlador.findWhere(new Articulo(), "estado=0");
        cargarDatos(listaArticulos);
    }

    public VSeleccionArticulo(int tipo) {
        initComponents();

        cmdSeleccionar.setEnabled(false);
        tipoI = tipo;
        listaArticulos = controlador.findEntities(controlador.getCount(art), 0, art);

        if (tipo == 1) {
            ReporteStockMinimo();
            jLabel2.setText("Articulos con cantidad Critica");
        } else {
            ReporteStock();
            jLabel2.setText("Stock Articulos");
        }
    }

    public void ReporteStock() {
        listaArticulos = controlador.findEntities(controlador.getCount(art), 0, art);
        cargarDatosStock(listaArticulos);
    }

    public void ReporteStockMinimo() {
        listaArticulos = controlador.findEntities(controlador.getCount(art), 0, art);
        List<Articulo> listaArticulos2;
        listaArticulos2 = listaArticulos;
        listaArticulos2.clear();
        listaArticulos = controlador.findEntities(controlador.getCount(art), 0, art);

        for (int i = 0; i < listaArticulos.size(); i++) {
            if (listaArticulos.get(i).getSminimo() >= listaArticulos.get(i).getStock()) {
                listaArticulos2.add(listaArticulos.get(i));
            }
        }
        cargarDatosStock(listaArticulos2);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cmdTodo = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgArticulos = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        txtMatch = new javax.swing.JTextField();
        cmdBuscar = new javax.swing.JButton();
        cmdSeleccionar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        cmdTodo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdTodo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/listar.png"))); // NOI18N
        cmdTodo.setText("    Mostrar Todos");
        cmdTodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdTodoActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 0, 153));
        jLabel2.setText("Seleccione un articulo");

        dtgArticulos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        dtgArticulos.setRowSorter(null);
        dtgArticulos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(dtgArticulos);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 51, 51));
        jLabel1.setText("Buscar en la tabla:");

        txtMatch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMatchActionPerformed(evt);
            }
        });
        txtMatch.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                txtMatchPropertyChange(evt);
            }
        });
        txtMatch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtMatchKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtMatchKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMatchKeyTyped(evt);
            }
        });

        cmdBuscar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        cmdBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar.png"))); // NOI18N
        cmdBuscar.setText("  Buscar");
        cmdBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdBuscarActionPerformed(evt);
            }
        });

        cmdSeleccionar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        cmdSeleccionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/select.png"))); // NOI18N
        cmdSeleccionar.setText("  Seleccionar");
        cmdSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdSeleccionarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtMatch, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(cmdBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(32, 32, 32)
                        .addComponent(cmdSeleccionar)
                        .addGap(148, 148, 148))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 724, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(cmdTodo))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(cmdTodo, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(9, 9, 9)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmdSeleccionar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtMatch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(cmdBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(8, 8, 8))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-764)/2, (screenSize.height-426)/2, 764, 426);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdTodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdTodoActionPerformed
        // TODO add your handling code here:

        if (tipoI == 1) {
            ReporteStockMinimo();
        }
        if (tipoI == 2) {
            ReporteStock();
        }
        if (tipoI == 0) {
            listaArticulos = controlador.findWhere(new Articulo(), "estado=0");
            cargarDatos(listaArticulos);
        }
    }//GEN-LAST:event_cmdTodoActionPerformed

    private void txtMatchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMatchActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtMatchActionPerformed

    private void txtMatchPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txtMatchPropertyChange
        // TODO add your handling code here:
    }//GEN-LAST:event_txtMatchPropertyChange

    private void txtMatchKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMatchKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {
            cmdBuscar.doClick();
        }
    }//GEN-LAST:event_txtMatchKeyPressed

    private void txtMatchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMatchKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtMatchKeyReleased

    private void txtMatchKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMatchKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_txtMatchKeyTyped

    private void cmdBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBuscarActionPerformed
        // TODO add your handling code here:
        if (this.txtMatch.getText().length() > 0) {
            this.listaArticulos = this.controlador.findHibernateSearch(this.art, this.txtMatch.getText(), new String[]{"codArticulo", "codigo", "descripcion", "marca", "modelo"});
            if (this.tipoI == 1) {
                List listaArticulos2 = this.listaArticulos;
                listaArticulos2.clear();
                this.listaArticulos = this.controlador.findHibernateSearch(this.art, this.txtMatch.getText(), new String[]{"codigo", "descripcion", "marca", "modelo"});

                for (int i = 0; i < this.listaArticulos.size(); i++) {
                    if (((Articulo) this.listaArticulos.get(i)).getSminimo().intValue() >= ((Articulo) this.listaArticulos.get(i)).getStock().intValue()) {
                        listaArticulos2.add(this.listaArticulos.get(i));
                    }
                }
                cargarDatosStock(listaArticulos2);
            }
            if (this.tipoI == 2) {
                cargarDatosStock(this.listaArticulos);
            }
            if (this.tipoI == 0) {
                cargarDatos(this.listaArticulos);
            }
        }
    }//GEN-LAST:event_cmdBuscarActionPerformed

    private void cmdSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSeleccionarActionPerformed
        // TODO add your handling code here:
        if (dtgArticulos.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(null, "Primero seleccione un Articulo", "Error", JOptionPane.ERROR_MESSAGE);
        } else {

            int i = dtgArticulos.getSelectedRow();
            CSelecciones.texto1.setText(listaArticulos.get(i).getCodigo().toString());

            CSelecciones.texto2.setText(listaArticulos.get(i).getPventa().toString());
            this.dispose();
        }
    }//GEN-LAST:event_cmdSeleccionarActionPerformed

    /**
     * @param args the command line arguments
     */
    private void cargarDatos(List<Articulo> listaArticulos) {
        MiModelo modelo = new MiModelo();
        String[] identificadores = {"Id", "Cod", "Descipcion", "Marca", "Modelo", "Precio Venta", "Stock", "IVA"};
        modelo.setColumnIdentifiers(identificadores);
        for (int i = 0; i < listaArticulos.size(); i++) {
            if (((Articulo) listaArticulos.get(i)).getEstado().intValue() == 0) {
                String[] articulo = {((Articulo) listaArticulos.get(i)).getCodigo().toString(), ((Articulo) listaArticulos.get(i)).getCodArticulo(), ((Articulo) listaArticulos.get(i)).getDescripcion(), ((Articulo) listaArticulos.get(i)).getMarca(), ((Articulo) listaArticulos.get(i)).getModelo(), String.valueOf(((Articulo) listaArticulos.get(i)).getPventa()), String.valueOf(((Articulo) listaArticulos.get(i)).getStock()), ((Articulo) listaArticulos.get(i)).getIva()};
                modelo.addRow(articulo);
            } else {
                listaArticulos.remove(i);
                i--;
            }
        }
        this.dtgArticulos.setModel(modelo);
        this.dtgArticulos.getColumn("Id").setPreferredWidth(25);
        this.dtgArticulos.getColumn("Descipcion").setPreferredWidth(200);
        this.dtgArticulos.getColumn("Marca").setPreferredWidth(120);
        this.dtgArticulos.getColumn("Modelo").setPreferredWidth(120);
        this.dtgArticulos.getColumn("Stock").setPreferredWidth(50);
        this.dtgArticulos.getColumn("IVA").setPreferredWidth(25);
    }

    private void cargarDatosStock(List<Articulo> listaArticulos) {
         MiModelo modelo = new MiModelo();
        String[] identificadores = {"Id", "Cod", "Descipcion", "Marca", "Modelo", "Precio Venta", "Stock", "IVA"};
        modelo.setColumnIdentifiers(identificadores);
        for (int i = 0; i < listaArticulos.size(); i++) {
            if (((Articulo) listaArticulos.get(i)).getEstado().intValue() == 0) {
                String[] articulo = {((Articulo) listaArticulos.get(i)).getCodigo().toString(), ((Articulo) listaArticulos.get(i)).getCodArticulo(), ((Articulo) listaArticulos.get(i)).getDescripcion(), ((Articulo) listaArticulos.get(i)).getMarca(), ((Articulo) listaArticulos.get(i)).getModelo(), String.valueOf(((Articulo) listaArticulos.get(i)).getPventa()), String.valueOf(((Articulo) listaArticulos.get(i)).getStock()), ((Articulo) listaArticulos.get(i)).getIva()};
                modelo.addRow(articulo);
            } else {
                listaArticulos.remove(i);
                i--;
            }
        }
        this.dtgArticulos.setModel(modelo);
        this.dtgArticulos.getColumn("Id").setPreferredWidth(25);
        this.dtgArticulos.getColumn("Descipcion").setPreferredWidth(200);
        this.dtgArticulos.getColumn("Marca").setPreferredWidth(120);
        this.dtgArticulos.getColumn("Modelo").setPreferredWidth(120);
        this.dtgArticulos.getColumn("Stock").setPreferredWidth(50);
        this.dtgArticulos.getColumn("IVA").setPreferredWidth(25);
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VSeleccionArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VSeleccionArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VSeleccionArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VSeleccionArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("Error setting native LAF: " + e);
        }
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VSeleccionArticulo(false).setVisible(true);
            }
        });
    }

   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdBuscar;
    private javax.swing.JButton cmdSeleccionar;
    private javax.swing.JButton cmdTodo;
    private javax.swing.JTable dtgArticulos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtMatch;
    // End of variables declaration//GEN-END:variables
}
